import request from 'umi-request'
import { Http } from '../../../../Common/Api'
import { API_LIST } from '../../../../Common/Api/Api'
import { useState, useEffect, useCallback, useRef } from 'react'
import { useBoolean, useRequest, useSize } from 'ahooks'
import { Button, Modal, Result } from 'antd'
import { ProTable } from '@ant-design/pro-components'

import { Player, BigPlayButton } from 'video-react'

// 更多的文件列表
const MoreBtn = ({ header, columns, parameter, style }) => {
    const [ModalState, { setTrue, setFalse }] = useBoolean(false)
    return (
        <>
            <div className="MoreBtn" style={style} onClick={setTrue}>
                更多&gt;&gt;
            </div>
            {ModalState && <MoreModalBox setFalse={setFalse} header={header} columns={columns} parameter={parameter} />}
        </>
    )
}

export const MoreModalBox = ({ setFalse, header, columns, parameter }) => {
    const { searchState, rowKey, api, title, scroll, data, path } = parameter
    const headers = { Authorization: sessionStorage.getItem('TOKEN') }
    const actionRef = useRef()
    return (
        <Modal
            className="MoreModal"
            open={true}
            onCancel={setFalse}
            destroyOnClose
            footer={null}
            keyboard={false}
            maskClosable={false}
            width={'80vw'}
            maskStyle={{ backgroundColor: 'rgba(0,0,0,0.8)' }}
        >
            <div className="header">{header}</div>
            <div className="body">
                <ProTable
                    defaultSize="small"
                    columns={columns}
                    actionRef={actionRef}
                    request={async (params = {}) => {
                        params.pageIndex = params.current
                        delete params.current
                        if (data) {
                            params = { ...params, ...data }
                        }
                        if (params.dateRange) {
                            params.startTime = params.dateRange[0]
                            params.endTime = params.dateRange[1]
                            delete params.dateRange
                        }
                        return request(API_LIST(path)[api], { params, headers }).then(res => {
                            return { data: res.list, success: true, total: res.total }
                        })
                    }}
                    columnsState={{ persistenceKey: 'pro-table-singe-demos', persistenceType: 'localStorage' }}
                    rowKey={rowKey ? rowKey : 'uuid'}
                    search={searchState ? true : false}
                    pagination={{ pageSize: 10 }}
                    dateFormatter="string"
                    headerTitle={title ? title : ''}
                    scroll={scroll}
                />
            </div>
        </Modal>
    )
}

export const Enclosure = ({ setFalse, header, columns, parameter }) => {
    const { rowKey, api, title, scroll, data } = parameter
    const headers = { Authorization: sessionStorage.getItem('TOKEN') }
    const actionRef = useRef()
    return (
        <Modal
            className="MoreModal"
            open={true}
            onCancel={setFalse}
            destroyOnClose
            footer={null}
            keyboard={false}
            maskClosable={false}
            width={'80vw'}
            maskStyle={{ backgroundColor: 'rgba(0,0,0,0.8)' }}
        >
            <div className="header">{header}</div>
            <div className="body">
                <ProTable
                    defaultSize="small"
                    columns={columns}
                    actionRef={actionRef}
                    request={async (params = {}) => {
                        params.pageIndex = params.current
                        delete params.current
                        if (data) {
                            params = { ...params, ...data }
                        }
                        if (params.dateRange) {
                            params.startTime = params.dateRange[0]
                            params.endTime = params.dateRange[1]
                            delete params.dateRange
                        }
                        return request(API_LIST()[api], { params, headers }).then(res => {
                            return { data: res.list, success: true, total: res.total }
                        })
                    }}
                    columnsState={{ persistenceKey: 'pro-table-singe-demos', persistenceType: 'localStorage' }}
                    rowKey={rowKey ? rowKey : 'uuid'}
                    search={false}
                    pagination={{ pageSize: 10 }}
                    dateFormatter="string"
                    headerTitle={title ? title : ''}
                    scroll={scroll}
                />
            </div>
        </Modal>
    )
}

export const One = ({ title, data, style, click }) => {
    const ContentBox = useRef()
    const size = useSize(ContentBox)
    const [height, setHeight] = useState(0)
    const [ListState, { setTrue, setFalse }] = useBoolean(false)

    useEffect(() => {
        if (size) {
            const { height } = size
            if (data.length > 0) {
                data.length * 54 > height ? setTrue() : setFalse()
                setHeight(height - 70)
            }
        }
    }, [data, setFalse, setTrue, size])

    return (
        <div className="TextOne" ref={ContentBox}>
            {height ? (
                <>
                    <div className="title" style={{ paddingRight: ListState ? 10 : 0 }}>
                        {title.map((item, index) => (
                            <div key={`TextOneTitle${index}`} style={{ flex: item.flex, background: style.background }}>
                                {item.title}
                            </div>
                        ))}
                    </div>
                    <div className="content" style={{ height, overflowY: ListState ? 'scroll' : 'hidden' }}>
                        {data.map((item, index) => (
                            <div
                                key={`TextOneContent${index}`}
                                onClick={() => click(item)}
                                style={{ borderColor: style.borderColor }}
                            >
                                {item.map((text, key) => {
                                    if (key < title.length)
                                        return (
                                            <div style={{ flex: title[key].flex }} key={`TextOneContentText${key}`}>
                                                <span> {text}</span>
                                            </div>
                                        )
                                    return false
                                })}
                            </div>
                        ))}
                    </div>
                </>
            ) : (
                <div className="NullData">
                    <Result title="暂无数据" />
                </div>
            )}
        </div>
    )
}

export const EnclosureDetails = ({ setFalse, url, header }) => {
    const ImageBox = ({ url }) => <img src={url} alt={url} />
    const PdfBox = ({ url }) => <embed src={url} style={{ height: '100%', width: '100%' }} />
    const VideoBox = ({ url }) => (
        <Player fluid={false} width={'100%'} height={'100%'} playsInline src={url}>
            <BigPlayButton position="center" />
        </Player>
    )
    const OtherBox = () => <Result status="500" title="文件格式不支持预览" />
    const [type, setType] = useState('ImageBox')
    const AttachmentList = {
        ImageBox,
        PdfBox,
        VideoBox,
        OtherBox,
    }
    useEffect(() => {
        var suffix = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
        if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif') {
            setType('ImageBox')
        } else if (suffix === 'pdf') {
            setType('PdfBox')
        } else if (suffix === 'mp4') {
            setType('VideoBox')
        } else {
            setType('OtherBox')
        }
    }, [url])

    return (
        <Modal
            className="MoreModal"
            open={true}
            onCancel={setFalse}
            destroyOnClose
            footer={null}
            keyboard={false}
            maskClosable={false}
            width={'80vw'}
            maskStyle={{ backgroundColor: 'rgba(0,0,0,0.8)' }}
        >
            <div className="header">{header}</div>
            <div className="body EnclosureDetails">
                {(() => {
                    const Template = AttachmentList[type]
                    return <Template url={url} />
                })()}
            </div>
        </Modal>
    )
}

// 文字列表
export const TextList = ({ header, TextTitle, InfoTypeManageUuid, columns, parameter, MoreStyle, ListStyle }) => {
    const [EnclosureState, { setTrue, setFalse }] = useBoolean(false)
    const [EnclosureDetailState, { setTrue: DetailTrue, setFalse: DetailFalse }] = useBoolean(false)
    const [EnclosureUUid, setEnclosureUUid] = useState('')
    const [EnclosureUrl, setEnclosureUrl] = useState('')
    const [getColumns, setColumns] = useState([])
    const [data, setData] = useState([])
    const { runAsync: getText } = useRequest(Http, { manual: true })
    const ViewDetails = useCallback(
        ({ uuid }) => {
            setEnclosureUUid(uuid)
            setTrue()
        },
        [setTrue],
    )
    useEffect(() => {
        let setData = JSON.parse(JSON.stringify(columns))
        if (setData.length > 0) {
            setData.find(v => v.dataIndex === 'infoTypeManageUuid').initialValue = InfoTypeManageUuid
            setColumns([
                ...setData,
                {
                    title: '附件',
                    search: false,
                    render: e => [
                        <Button type="link" key="Content" onClick={() => ViewDetails(e)}>
                            详情
                        </Button>,
                    ],
                },
            ])
        }
    }, [InfoTypeManageUuid, ViewDetails, columns])
    useEffect(() => {
        getText({ url: 'getConstructionInfoManageStat', data: { InfoTypeManageUuid, OEventDate: 'desc@1' } }).then(
            ({ list }) => {
                let data = []
                list.forEach(item => (data = [...data, [item.tableName, item.eventDate, item.uuid]]))
                setData(data)
            },
        )
    }, [InfoTypeManageUuid, getText])
    const textClick = e => {
        setEnclosureUUid(e.at(-1))
        setTrue()
    }

    let EnclosureData = [
        {
            title: '说明',
            dataIndex: 'tableName',
            ellipsis: true,
            align: 'left',
        },
        {
            title: '操作',
            width: 150,
            render: ({ fileUrl }) => [
                <Button
                    type="link"
                    key="see"
                    onClick={() => {
                        setEnclosureUrl(fileUrl)
                        DetailTrue()
                    }}
                >
                    详情
                </Button>,
            ],
        },
    ]

    return (
        <>
            <MoreBtn style={MoreStyle} header={header} columns={getColumns} parameter={parameter} />
            <One title={TextTitle} data={data} style={ListStyle} click={textClick} />
            {EnclosureState && (
                <Enclosure
                    header={header}
                    setFalse={setFalse}
                    columns={EnclosureData}
                    parameter={{ api: 'getConstructionInfoManageDetail', data: { InfoManageUuid: EnclosureUUid } }}
                />
            )}
            {EnclosureDetailState && <EnclosureDetails header={header} url={EnclosureUrl} setFalse={DetailFalse} />}
        </>
    )
}

export const EnclosureDetailsLin = ({ setFalse, url, header }) => {
    console.log(url)
    const ImageBox = ({ url }) => <img src={url} alt={url} />
    const PdfBox = ({ url }) => <embed src={url} style={{ height: '100%', width: '100%' }} />
    const VideoBox = ({ url }) => (
        <Player fluid={false} width={'100%'} height={'100%'} playsInline src={url}>
            <BigPlayButton position="center" />
        </Player>
    )
    const OtherBox = () => <Result status="500" title="文件格式不支持预览" />
    const [type, setType] = useState('ImageBox')
    const AttachmentList = {
        ImageBox,
        PdfBox,
        VideoBox,
        OtherBox,
    }
    useEffect(() => {
        var suffix = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
        if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif') {
            setType('ImageBox')
        } else if (suffix === 'pdf') {
            setType('PdfBox')
        } else if (suffix === 'mp4') {
            setType('VideoBox')
        } else {
            setType('OtherBox')
        }
    }, [url])

    return (
        <Modal
            className="MoreModal"
            open={true}
            onCancel={setFalse}
            destroyOnClose
            footer={null}
            width={'80vw'}
            closable={false}
        >
            <div className="header">{header}</div>
            <div className="body EnclosureDetails">
                {(() => {
                    const Template = AttachmentList[type]
                    return <Template url={url} />
                })()}
            </div>
        </Modal>
    )
}
